import xlsx from "xlsx";
import path from "path";
import {forEach, isNil, keys} from "lodash";
import {formatToDate} from "../../utils/dateUtil";
import { v4 as uuidv4 } from 'uuid';
export const readExcel =(filename:string,sheetIndex=2,version=1)=>{
    const workbook = xlsx.readFile(path.resolve(__dirname,'../../../')+'/data/'+filename,{cellDates:true,cellText:true });
    const name = workbook.SheetNames[sheetIndex];
    const sheet = workbook.Sheets[name];
    let results = xlsx.utils.sheet_to_json(sheet,{defval:'',raw:true })as Object[]
    const fields ={
        "投放日期":'put_in_date',
        "投放方式":'put_in_type',
        "达人":'talent',
        "排期ID":'schedule_id',
        "计划ID":'plan_id',
    };
    const data =[];
    for (const key in results) {
        if ( results[key]['投放日期'] instanceof Date){
            const arr = {};
            forEach(keys(results[key]),(itemkey)=>{
                if (!isNil(fields[itemkey])){
                    if (fields[itemkey] =='put_in_date'){
                        arr[fields[itemkey]] = formatToDate(results[key][itemkey] as Date);
                    }else{
                        arr[fields[itemkey]] = results[key][itemkey];
                    }
                }
                if (itemkey.indexOf('EMPTY')!=-1){
                    delete results[key][itemkey];
                }
            })
            arr['content'] = JSON.stringify(results[key]);
            arr['uuid'] = uuidv4();
            arr['versions'] = version;
            data.push(arr);
        }
    }
    return data;
}